package com.originskyseed.platform.role.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.role.i18n.RoleResponseMsg;
import com.originskyseed.platform.role.model.Menu;
import com.originskyseed.platform.role.model.Role;
import com.originskyseed.platform.role.service.IMenuService;
import com.originskyseed.platform.role.service.IRoleRelMenuService;
import com.originskyseed.platform.role.service.IRoleRelUserService;
import com.originskyseed.platform.role.service.IRoleService;
import com.originskyseed.platform.role.vo.request.RoleListRequestVO;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 角色表Controller类（OSI_ROLE）
 *
 * @author LiangMingHui
 *
 */
@Controller
@RequestMapping("/role")
@BaseLocaleResource(localeFileName = "i18n_role")
public class RoleController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

	@DubboReference
	private IRoleService roleService;

	@DubboReference
	private IRoleRelUserService roleRelUserService;

	@DubboReference
	private IRoleRelMenuService roleRelMenuService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IMenuService menuService;

	/**
	 * 根据id查询角色详情
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectRoleById.json")
	@RequiredParams(names = { "id" })
	public BaseResponseBody selectRoleById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			if (StringUtils.isNotBlank(id)) {
				Role role = this.roleService.selectByPrimaryKey(id);
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.QUERY_ID_SUCCESS.getMsg()), role);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.QUERY_ID_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询角色列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody roleList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			RoleListRequestVO requestVO = this.getParameterBean(RoleListRequestVO.class);
			requestVO.setIsDel(2);
			// 分页查询
			BasePage<Role> page = new BasePage<Role>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.roleService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询角色列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleListAll.json")
	public BaseResponseBody roleListAll(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			Role role = this.getParameterBean(Role.class);
			role.setStatus(1);
			role.setIsDel(2);
			// 分页查询
			List<Role> roleList = this.roleService.selectList(role);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_LIST_SUCCESS.getMsg()), roleList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存角色信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleSave.json")
	@RequiredParams(names = { "name" })
	public BaseResponseBody roleSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			Role role = this.getParameterBean(Role.class);
			if (StringUtils.isNotBlank(role.getId())) {
				Role queryRole = this.roleService.selectByPrimaryKey(role.getId());
				if (role.getBelongPlatform() != queryRole.getBelongPlatform()) {
					if (this.roleRelUserService.existUserId(role.getId())) {
						return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_UPDATE_EXIST_USER_ERROR.getMsg()), null);
					}
				}
				this.roleService.updateByPrimaryKeySelective(role);
			} else {
				Integer prority = this.roleService.selectPrority();
				if (prority != null) {
					prority += 1;
				} else {
					prority = 1;
				}
				role.setPriority(prority);
				role.setIsTop(0);
				role.setStatus(1);
				role.setCreatorId(userInfo.getId());
				role.setCreator(userInfo.getName());
				role.setIsDel(2);
				role.setCode(this.roleService.selectRoleCode());
				this.roleService.insertSelective(role);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_SAVE_SUCCESS.getMsg()), role);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除角色信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleDelete.json")
	@RequiredParams(names = { "ids" })
	public BaseResponseBody roleDelete(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			if (this.roleRelUserService.existUserId(Arrays.asList(ids))) { // 判断是否存在用户关联记录
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_DELETE_EXIST_USER_ERROR.getMsg()), false);
			} else if (this.roleRelMenuService.existPermissionId(Arrays.asList(ids))) { // 判断是否存在权限关联记录
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_DELETE_EXIST_PERMISSION_ERROR.getMsg()), false);
			} else {
				Map<String, Object> map = new HashMap<>();
				map.put("list", Arrays.asList(ids));
				map.put("isDel", 1);
				this.roleService.updateIsDelByIds(map);
				//this.roleService.deleteByPrimaryKeys(Arrays.asList(ids));
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_DELETE_SUCCESS.getMsg()), true);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 启用/禁用
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleUpdateStatus.json")
	@RequiredParams(names = { "ids", "status" })
	public BaseResponseBody roleUpdateStatus(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			Integer status = this.getParameterInteger("status", null);

			Map<String, Object> map = new HashMap<>();
			map.put("list", Arrays.asList(ids));
			map.put("status", status);

			this.roleService.updateStatusByIds(map);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_UPDATE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_UPDATE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 角色绑定用户信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleBindUserInfo.json")
	@RequiredParams(names = { "roleId" })
	public BaseResponseBody roleBindUserInfo(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String roleId = this.getParameterString("roleId", null);
			String[] userIds = this.getParameterArray("userIds", new String[] {});

			List<String> userIdList = Arrays.asList(userIds);
			this.roleRelUserService.deleteAndInsertByRoleId(roleId, userIdList);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_USER_INFO_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_USER_INFO_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 角色绑定权限信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleBindPermission.json")
	@RequiredParams(names = { "roleId" })
	public BaseResponseBody roleBindPermission(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			String mallId = null;
			// 请求参数
			String roleId = this.getParameterString("roleId", null);
			String[] permissionIds = this.getParameterArray("permissionIds", new String[] {});
			List<String> permissionIdList = Arrays.asList(permissionIds);

			Role role = this.roleService.selectByPrimaryKey(roleId);
			if (role != null) {
				this.roleRelMenuService.deleteAndInsertByRoleId(roleId, permissionIdList);
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_PERMISSION_SUCCESS.getMsg()), true);
			} else {
				result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_PERMISSION_ERROR.getMsg()), null);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_PERMISSION_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 角色绑定权限回显
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleBindPermissionSelect.json")
	@RequiredParams(names = { "roleId" })
	public BaseResponseBody roleBindPermissionSelect(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String roleId = this.getParameterString("roleId", null);
			Role role = this.roleService.selectByPrimaryKey(roleId);

			JSONArray jsonArray = this.roleService.roleBindPermissionSelectListAdmin(roleId, role.getBelongPlatform());
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_PERMISSION_TREE_SUCCESS.getMsg()), jsonArray);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_PERMISSION_TREE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 修改置顶信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateIsTop.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody updateIsTop(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer prority = this.roleService.selectPrority();

			Role role = new Role();
			role.setId(id);
			role.setIsTop(1);
			role.setPriority(prority + 1);
			this.roleService.updateIsTop(role);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 升序降序
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUpOrDown.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id", "upOrDown", "prority" })
	public BaseResponseBody updateUpAndDown(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer upOrDown = this.getParameterInteger("upOrDown", null);

			// 查询出优先级
			Role queryRole = this.roleService.selectByPrimaryKey(id);
			Integer priority = queryRole.getPriority();

			Map<String, Object> map = new HashMap<>();
			map.put("type", upOrDown);
			map.put("priority", priority);
			// 将另外一个升序或降序
			Role role = this.roleService.selectByPrioritySort(map);

			Role updateRole = new Role();
			updateRole.setId(id);
			if (role != null) {
				updateRole.setPriority(role.getPriority());
				role.setPriority(priority);
			} else {
				// 等于0是升序 1是降序
				if (upOrDown == 0) {
					updateRole.setPriority(priority + 1);
				} else {
					updateRole.setPriority(priority - 1);
				}
			}

			if (role != null) {
				this.roleService.updatePrority(role, updateRole);
			} else {
				this.roleService.updateByPrimaryKeySelective(updateRole);
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.DATA_SAVE_SUCCESS.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据菜单code查询按钮权限
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectButtonLevelByCode.json")
	public BaseResponseBody selectButtonLevelByCode(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 获取当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求参数
			String permissionCode = this.getParameterString("permissionCode", null);

			List<Menu> menuList = this.menuService.selectButtonLevelByCode(permissionCode, userInfo.getRoleId());
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_PERMISSION_TREE_SUCCESS.getMsg()), menuList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RoleResponseMsg.ROLE_BIND_PERMISSION_TREE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

}
